package com.yun.zf.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.ZfOrderMapper;
import com.yun.zf.admin.service.ZfHouseBasicService;
import com.yun.zf.admin.service.ZfOrderService;
import com.yun.zf.admin.service.ZfPerformanceService;
import com.yun.zf.admin.service.ZfSubOrderService;
import com.yun.zf.common.admin.domain.SysDept;
import com.yun.zf.common.admin.domain.ZfOrder;
import com.yun.zf.common.admin.dto.order.OrderSearchResMo;
import com.yun.zf.common.admin.dto.PerformanceDto;
import com.yun.zf.common.admin.dto.order.OrderInfoDto;
import com.yun.zf.common.admin.dto.order.SubOrderDto;
import com.yun.zf.common.admin.dto.pact.OrderDto;
import com.yun.zf.common.admin.model.order.CreateOrderMo;
import com.yun.zf.common.admin.model.order.OrderMo;
import com.yun.zf.common.admin.model.order.PerformanceMo;
import com.yun.zf.common.admin.model.pact.OrderSearchMo;
import com.yun.zf.common.admin.model.search.OrderIndexKey;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.esIndex.OrderIndexTemplate;
import com.yun.zf.common.esRes.OrderIndexResMo;
import com.yun.zf.common.mapstruct.admin.OrderMapper;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.ISysDeptService;
import com.yun.zf.system.service.SysUserAuthService;
import com.yun.zf.system.utils.EsRestUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-07-27
 */
@Service
public class ZfOrderServiceImpl extends ServiceImpl<ZfOrderMapper, ZfOrder> implements ZfOrderService {
    @Autowired
    private ZfSubOrderService detailService;
    @Autowired
    private ZfPerformanceService performanceService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private EsRestUtil esRestUtil;
    @Autowired
    SysUserAuthService authService;
    @Autowired
    private ZfHouseBasicService basicService;
    @Autowired
    private ZfSubOrderService pactAmountDetailService;

    @Override
    @Transactional
    public Long creatOrder(OrderMo orderMo, Long provCode, Long cityCode) {
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        // 获取部门名称
        SysDept dept = deptService.getDeptByDeptId(deptId);
        ZfOrder order = OrderMapper.INSTANCE.moToOrder(orderMo.getBasicMo());
        order.setCityCode(cityCode);
        order.setProvinceCode(provCode);
        order.setSignAgent(agentNo);
        order.setSignName(SecurityUtils.getLoginUser().getAgentName());
        order.setStatus("INIT");
        order.setCreateTime(new Date());
        order.setDeptId(deptId);
        order.setDeptName(dept.getDeptName());
        if (order.getType().equals("1")) {
            order.setPriceUnit("元");
        } else if (order.getType().equals("2")) {
            order.setPriceUnit("万元");
        }
        // 保存订单信息
        baseMapper.insert(order);
        // 保存子订单信息
        //2、保存订单金额分项明细
        detailService.addOrderDetail(provCode, cityCode, order.getId(), orderMo.getDetailMos());
        // 获取维护人信息
        List<Map<String, Object>> list = basicService.getAgent(order.getHouseId(), provCode, cityCode);
        PerformanceMo pf = new PerformanceMo();
        for (Map<String, Object> map : list
        ) {
            if (map.get("record_name") != null) {
                pf.setAgentName(map.get("record_name").toString());
            }
            if (map.get("record_user") != null) {
                pf.setAgentNo(map.get("record_user").toString());
            }
            if (map.get("dept_id") != null) {
                pf.setDeptId(map.get("dept_id").toString());
            }
        }
        List<PerformanceMo> pslit = orderMo.getPerformanceMos();
        if (pslit == null) {
            pslit = new ArrayList<>();
        }
        pslit.add(pf);

        //3 合作信息
        performanceService.addPerformance(provCode, cityCode, order.getId(), order.getAmount(), pslit);

        return order.getId();
    }

    @Override
    @Transactional
    public int  editOrder(OrderMo orderMo, Long provCode, Long cityCode) {
        //1、查询订单
        QueryWrapper<ZfOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ZfOrder::getId,orderMo.getId()).eq(ZfOrder::getCityCode,cityCode).eq(ZfOrder::getProvinceCode,provCode);
       ZfOrder order =  baseMapper.selectOne(wrapper);
        BeanUtil.copyProperties(orderMo.getBasicMo(), order, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
      int c=  baseMapper.update(order,wrapper);
        // 删除子订单信息
        detailService.delSubOrders(provCode,cityCode,Long.parseLong(orderMo.getId()));
        //2、保存订单金额分项明细
        detailService.addOrderDetail(provCode, cityCode, order.getId(), orderMo.getDetailMos());
        // 3 删除合作信息
        performanceService.delPerFormance(provCode,cityCode,order.getId());
        // 新增合作信息
        //3 合作信息
        performanceService.addPerformance(provCode, cityCode, order.getId(), order.getAmount(), orderMo.getPerformanceMos());
        return c;
    }

    @Override
    public ZfOrder getOrderByOrderId(Long provCode, Long cityCode, Long orderId) {
        QueryWrapper<ZfOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(ZfOrder::getId, orderId).eq(ZfOrder::getCityCode, cityCode).eq(ZfOrder::getProvinceCode, provCode);
        return baseMapper.selectOne(orderQueryWrapper);
    }

    @Override
    public List<OrderSearchResMo> getOrderlist(Long provCode, Long cityCode, List<Long> ids) {
        return baseMapper.getOrderList(provCode, cityCode, ids);
    }

    @Override
    public Page<OrderSearchResMo> getOrderRes(OrderSearchMo search, Long provCode, Long cityCode, int agentNo) {
        Page<OrderSearchResMo> page = new Page<>(search.getCurrent(), search.getPageSize());
        page.setRecords(baseMapper.getOrderSearch(search, provCode, cityCode, agentNo, page));
        return page;
    }

    @Override
    public Map<String, Object> orderSearch(OrderSearchMo search, Long provCode, Long cityCode, int agentNo) {
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        // 查询只返回小区ID 字段
        String[] fields = new String[]{OrderIndexKey.OID, OrderIndexKey.PROVINCECODE, OrderIndexKey.CITYCODE};
        //1 、 构建搜索条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // 2、城市代码必传-----
        queryBuilder.must(QueryBuilders.termQuery(OrderIndexKey.CITYCODE, cityCode));
        // 3、类型type必传-----
        queryBuilder.must(QueryBuilders.termQuery(OrderIndexKey.TYPE, search.getType()));
        // 4、 房源编号不为空直接匹配
        if (StringUtils.isNotBlank(search.getHouseId())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.HOUSEID, search.getHouseId()));
        }
        // 客户姓名不为空
        if (StringUtils.isNotBlank(search.getCusName())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.CUSNAME, search.getCusName()));
        }
        if (StringUtils.isNotBlank(search.getCusIphone())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.CUSIPHONE, search.getCusIphone()));
        }
        if (StringUtils.isNotBlank(search.getOwnName())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.OWNNAME, search.getOwnName()));
        }
        if (StringUtils.isNotBlank(search.getOwnIphone())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.OWNIPHONE, search.getOwnIphone()));
        }
        if (StringUtils.isNotBlank(search.getStatus())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.STATUS, search.getStatus()));
        }
        if (StringUtils.isNotBlank(search.getAgentNo())) {
            queryBuilder.filter(QueryBuilders.termQuery(OrderIndexKey.AGENTNO, search.getAgentNo()));
        }

        searchQueryBuilder.withQuery(queryBuilder).withFields(fields);
        Map<String, Object> orderData = esRestUtil.searchDataPage(Constants.ES_ORDER_INDEX, search.getCurrent(), search.getPageSize(), OrderIndexResMo.class, searchQueryBuilder);
        return orderData;
    }

    @Override
    public OrderDto orderDetail(Long orderId, Long provCode, Long cityCode) {
        // 订单基本信息
        OrderInfoDto orderInfoDto = getOrderInfo(orderId, provCode, cityCode);
        //1、 获取合同基本信息
        // PactInfoMo pactInfoMo = pactService.getPactInfo(provCode, cityCode, orderId);
        //2、 获取款项详情
        List<SubOrderDto> details = pactAmountDetailService.getDetails(provCode, cityCode, orderId);
        for (SubOrderDto sub : details
        ) {
            if (sub.getMoneyType() == 1) {
                sub.setName(orderInfoDto.getOwnName());
                sub.setIphone(orderInfoDto.getOwnIphone());
            } else if (sub.getMoneyType() == 2) {
                sub.setName(orderInfoDto.getCusName());
                sub.setIphone(orderInfoDto.getCusIphone());
            }
        }
        //3、 获取业绩分配详情
        List<PerformanceDto> performanceDtos = performanceService.getPerformances(provCode, cityCode, orderId);
        OrderDto orderDto = new OrderDto();
        orderDto.setOrderInfoDto(orderInfoDto);
        orderDto.setAmountDetails(details);
        orderDto.setPerformanceDtos(performanceDtos);
        return orderDto;
    }

    @Override
    public void getOrderEs(Long orderId, Long provCode, Long cityCode) {
        OrderIndexTemplate orderIndex = baseMapper.getOrderEs(provCode, cityCode, orderId);
        String res = esRestUtil.addDataRest(orderIndex, Constants.ES_ORDER_INDEX, orderId.toString());
    }

    @Override
    public OrderInfoDto getOrderInfo(Long orderId, Long provCode, Long cityCode) {
        QueryWrapper<ZfOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(ZfOrder::getId, orderId).eq(ZfOrder::getCityCode, cityCode).eq(ZfOrder::getProvinceCode, provCode);
        ZfOrder order = baseMapper.selectOne(orderQueryWrapper);
        OrderInfoDto orderInfoDto = OrderMapper.INSTANCE.orderToDto(order);
        return orderInfoDto;
    }

    @Override
    public OrderMo bringOrder(Long orderId, Long provCode, Long cityCode) {
        // 1、 查询基本信息
        CreateOrderMo basic = baseMapper.bringOrder(provCode,cityCode,orderId);
        //2、 获取合作信息
        List<PerformanceMo> pfMos = performanceService.bringPerformances(provCode, cityCode, orderId);
        OrderMo mo = new OrderMo();
        mo.setBasicMo(basic);
        mo.setPerformanceMos(pfMos);
        mo.setId(String.valueOf(orderId));
        return mo;
    }
}
